package com.mit.web.view.component.monitor
{
	import flash.display.DisplayObject;
	
	import mx.controls.ProgressBar;
	import mx.controls.ProgressBarLabelPlacement;
	import mx.controls.ProgressBarMode;
	import mx.core.Container;
	import mx.managers.PopUpManager;
	
	import spark.components.BorderContainer;
	import spark.components.VGroup;
	
	public class ProgressBarMonitor implements IProgressMonitor
	{
		private static var _me:ProgressBarMonitor;
		private var _control:ProgressBar;
		private var _container:VGroup;
		private var _tokens:Array;
		private var _topmost:IMonitorToken;
		
		public function ProgressBarMonitor()
		{
			_tokens = new Array();
			_container = new VGroup();
			_control = new ProgressBar();
			_control.width = 175;
			_control.labelPlacement = ProgressBarLabelPlacement.TOP;

			_control.indeterminate = true;
			_control.minimum = 0;
			_control.maximum = 100;

			_control.mode = ProgressBarMode.MANUAL;
			_container.addElement(_control);
		}
		
		public static function getInstance():IProgressMonitor{
			if(_me == null)
				_me = new ProgressBarMonitor();
			return _me;
		}
		
		public function begin(target:Object, parent:DisplayObject, cancelHandler:Function=null):IMonitorToken
		{
			var token:MonitorToken = new MonitorToken(this, target, parent, cancelHandler);
			show(token);
			_tokens.push(token);
			return token;
		}
		
		public function update(token:IMonitorToken, curValue:Number=-1, label:String=null):void
		{
			if(token){
				if(curValue > -1) token.curValue = curValue;
				if(label) token.label = label;
				if(_topmost == token){
					_control.label = token.label;
					_control.minimum = token.minValue;
					_control.setProgress(token.curValue, token.maxValue);
				}
			}
		}
		
		private function show(token:IMonitorToken):void{
			hide();
			if(token){
				_topmost = token;
				_control.label = token.label;
				PopUpManager.addPopUp(_container, token.parent, true);
				PopUpManager.centerPopUp(_container);
				PopUpManager.bringToFront(_container);
				
			}
		}
		
		private function hide():void{
			if(_container.isPopUp)
				PopUpManager.removePopUp(_container);
		}
		
		public function stop(token:IMonitorToken):void
		{
			if(token){
				if(removeToken(token)){
					if(_tokens.length == 0)
						hide();
					else if (_topmost == token){
						_topmost = _tokens[_tokens.length -1];
						show(_topmost);
					}
				}
			}
		}
		
		private function removeToken(token:IMonitorToken):Boolean{
			var index:int = _tokens.indexOf(token);
			if(index > -1){
				_tokens.splice(index, 1);
				return true;
			}
			return false;
		}
	}
}